package com.ypx.ec.cart.interceptor;

import com.ypx.ec.cart.vo.UserInfoTo;
import com.ypx.ec.common.constant.AuthServerConstant;
import com.ypx.ec.common.constant.CartConstant;
import com.ypx.ec.common.vo.MemberRespVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * 在执行目标方法前,先判断用户登录状态。并封装用户信息传递给Controller
 */

@Slf4j
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    /*
    目标方法之前拦截
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        UserInfoTo userInfoTo = new UserInfoTo();
        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);

        if (member != null) {
            //用户登录
            userInfoTo.setUserId(member.getId());
            threadLocal.set(userInfoTo);
            return true;
        }else{
            //跳转登录页
            request.getSession().setAttribute("msg","请先登录");
            response.sendRedirect("http://auth.ec.ypx.com/login.html");
            return false;
        }


    }


}
